import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    // 文档管理
    documents: [],
    currentDocument: null,
    documentVersions: [],
    
    // 知识分类
    categories: [
      {
        id: 1,
        label: '土建工程',
        children: [
          { id: 11, label: '结构' },
          { id: 12, label: '基础' },
          { id: 13, label: '主体' }
        ]
      },
      {
        id: 2,
        label: '机电工程',
        children: [
          { id: 21, label: '给排水' },
          { id: 22, label: '暖通' },
          { id: 23, label: '电气' },
          { id: 24, label: '弱电' },
          { id: 25, label: '消防' }
        ]
      },
      {
        id: 3,
        label: '装修工程',
        children: [
          { id: 31, label: '内装' },
          { id: 32, label: '外装' },
          { id: 33, label: '特殊装修' }
        ]
      },
      {
        id: 4,
        label: '市政工程',
        children: [
          { id: 41, label: '道路' },
          { id: 42, label: '桥梁' },
          { id: 43, label: '管网' },
          { id: 44, label: '园林' }
        ]
      }
    ],
    tags: [],
    
    // 知识条目
    knowledgeItems: [
      {
        id: 1,
        title: '基础施工规范',
        type: '文本',
        importance: '关键',
        updateTime: '2024-01-20 10:00:00',
        content: '基础施工的标准流程和注意事项...',
        tags: ['施工规范', '基础工程'],
        categoryId: 12
      }
    ],
    
    // ID计数器
    nextCategoryId: 5,
    nextKnowledgeId: 2,
    
    // 数字人设置
    avatarSettings: {
      type: 'engineer', // engineer, technician, architect
      gender: 'male', // male, female, neutral
      expression: 'normal', // normal, thinking, smiling, explaining
      language: 'mandarin', // mandarin, cantonese, sichuan, dongbei
      age: 35, // 年龄设置
      voice: {
        speed: 1.0,
        pitch: 0,
        volume: 1.0
      },
      emotionRecognition: true,
      multiDialectSupport: true
    },
    
    // 对话管理
    conversationHistory: [],
    currentTopic: null,
    userIntent: null
  }),
  
  actions: {
    // 文档操作
    uploadDocument(doc) {
      this.documents.push(doc)
    },
    updateDocument(id, updates) {
      const index = this.documents.findIndex(d => d.id === id)
      if (index > -1) {
        this.documents[index] = { ...this.documents[index], ...updates }
      }
    },
    
    // 知识分类操作
    addCategory(categoryData) {
      const newCategory = {
        id: this.nextCategoryId++,
        label: categoryData.name,
        children: []
      };
      
      if (categoryData.parent) {
        const parentId = categoryData.parent;
        const findAndAdd = (cats) => {
          for (let cat of cats) {
            if (cat.id === parentId) {
              cat.children = cat.children || [];
              cat.children.push(newCategory);
              return true;
            }
            if (cat.children && findAndAdd(cat.children)) {
              return true;
            }
          }
          return false;
        };
        
        findAndAdd(this.categories);
      } else {
        // 添加为顶级分类
        this.categories.push(newCategory);
      }
    },
    
    editCategory(categoryData) {
      if (!categoryData.id) {
        throw new Error("分类ID不能为空");
      }
      
      if (!categoryData.name) {
        throw new Error("分类名称不能为空");
      }
      
      const findAndUpdate = (cats) => {
        for (let cat of cats) {
          if (cat.id === categoryData.id) {
            cat.label = categoryData.name;
            return true;
          }
          if (cat.children && findAndUpdate(cat.children)) {
            return true;
          }
        }
        return false;
      };
      
      findAndUpdate(this.categories);
    },
    
    deleteCategory(categoryId) {
      if (!categoryId) {
        throw new Error("分类ID不能为空");
      }
      
      // 查找要删除的分类及其所有子分类
      const findAllCategoryIds = (cats) => {
        let ids = [];
        cats.forEach(cat => {
          ids.push(cat.id);
          if (cat.children && cat.children.length > 0) {
            ids = ids.concat(findAllCategoryIds(cat.children));
          }
        });
        return ids;
      };
      
      const findAndDelete = (cats) => {
        for (let i = 0; i < cats.length; i++) {
          if (cats[i].id === categoryId) {
            // 找到要删除的分类，获取该分类及其所有子分类的ID
            const allCategoryIds = findAllCategoryIds([cats[i]]);
            // 删除该分类下的所有知识
            this.knowledgeItems = this.knowledgeItems.filter(item => !allCategoryIds.includes(item.categoryId));
            // 删除该分类
            cats.splice(i, 1);
            return true;
          }
          if (cats[i].children && findAndDelete(cats[i].children)) {
            return true;
          }
        }
        return false;
      };
      
      findAndDelete(this.categories);
    },
    
    addTag(tag) {
      this.tags.push(tag)
    },
    
    // 知识条目操作
    addKnowledge(knowledgeData) {
      if (!knowledgeData.title) {
        throw new Error("知识标题不能为空");
      }
      
      if (!knowledgeData.categoryId) {
        throw new Error("请选择分类");
      }
      
      const newKnowledge = {
        id: this.nextKnowledgeId++,
        title: knowledgeData.title,
        type: knowledgeData.type || '文本',
        importance: knowledgeData.importance || '一般',
        content: knowledgeData.content || '',
        tags: knowledgeData.tags || [],
        updateTime: new Date().toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit', 
          hour: '2-digit', 
          minute: '2-digit', 
          second: '2-digit' 
        }).replace(/\//g, '-'),
        categoryId: knowledgeData.categoryId
      };
      
      this.knowledgeItems.push(newKnowledge);
      return newKnowledge;
    },
    
    deleteKnowledge(knowledgeId) {
      if (!knowledgeId) {
        throw new Error("知识ID不能为空");
      }
      
      const index = this.knowledgeItems.findIndex(item => item.id === knowledgeId);
      if (index > -1) {
        this.knowledgeItems.splice(index, 1);
      } else {
        throw new Error("知识不存在");
      }
    },
    
    editKnowledge(knowledgeData) {
      if (!knowledgeData.id) {
        throw new Error("知识ID不能为空");
      }
      
      if (!knowledgeData.title) {
        throw new Error("知识标题不能为空");
      }
      
      if (!knowledgeData.categoryId) {
        throw new Error("请选择分类");
      }
      
      const index = this.knowledgeItems.findIndex(item => item.id === knowledgeData.id);
      if (index > -1) {
        this.knowledgeItems[index] = {
          ...this.knowledgeItems[index],
          title: knowledgeData.title,
          type: knowledgeData.type || '文本',
          importance: knowledgeData.importance || '一般',
          content: knowledgeData.content || '',
          tags: knowledgeData.tags || [],
          categoryId: knowledgeData.categoryId,
          updateTime: new Date().toLocaleString('zh-CN', { 
            year: 'numeric', 
            month: '2-digit', 
            day: '2-digit', 
            hour: '2-digit', 
            minute: '2-digit', 
            second: '2-digit' 
          }).replace(/\//g, '-')
        };
      } else {
        throw new Error("知识不存在");
      }
    },
    
    // 数字人设置
    updateAvatarSettings(settings) {
      this.avatarSettings = { ...this.avatarSettings, ...settings }
    },
    
    // 对话管理
    addToHistory(message) {
      this.conversationHistory.push(message)
    },
    setCurrentTopic(topic) {
      this.currentTopic = topic
    },
    setUserIntent(intent) {
      this.userIntent = intent
    },
    
    // 初始化数据（从localStorage加载）
    initFromStorage() {
      if (typeof localStorage !== 'undefined') {
        const storedState = localStorage.getItem('appStore');
        if (storedState) {
          try {
            const parsed = JSON.parse(storedState);
            // 合并存储的状态与当前状态
            Object.assign(this, parsed);
          } catch (e) {
            console.error('从localStorage恢复状态失败:', e);
          }
        }
      }
    },
    
    // 保存到localStorage
    saveToStorage() {
      if (typeof localStorage !== 'undefined') {
        try {
          // 创建一个不包含方法的纯数据对象
          const stateToSave = {
            categories: this.categories,
            tags: this.tags,
            knowledgeItems: this.knowledgeItems,
            nextCategoryId: this.nextCategoryId,
            nextKnowledgeId: this.nextKnowledgeId,
            documents: this.documents,
            currentDocument: this.currentDocument,
            documentVersions: this.documentVersions,
            avatarSettings: this.avatarSettings,
            conversationHistory: this.conversationHistory,
            currentTopic: this.currentTopic,
            userIntent: this.userIntent
          };
          localStorage.setItem('appStore', JSON.stringify(stateToSave));
        } catch (e) {
          console.error('保存状态到localStorage失败:', e);
        }
      }
    }
  }
})